﻿using UnityEngine;
using System.Collections;

public class ExpHUDText : MonoBehaviour {
	public UILabel label;
	public UISprite image;
	public UIAtlas battleAtlas;
	public UIAtlas battleResultAtlas;

	public bool isDone = false;

	void Start()
	{
//		SetExpValue(99);
		if( label == null )
			label = GetComponentInChildren<UILabel>();
	}

	public void SetExpValue(int endValue)
	{
		isDone = false;
		GetComponent<UIFollowTarget>().enabled = true;
		gameObject.SetActive(true);
		Vector3 pos = label.transform.localPosition;
		pos.y += 90f;
		TweenPosition posTween = TweenPosition.Begin(label.gameObject, 1f, pos);
		posTween.from = label.transform.localPosition + new Vector3(0f, 30f, 0f);
		posTween.delay = 0.5f;
		StartCoroutine(Co_SetExpValue(endValue));
	}

	public void ShowLevelUpImage()
	{
		isDone = false;
		GetComponent<UIFollowTarget>().enabled = true;
		image.atlas = battleResultAtlas;
		image.spriteName = "exp_text_levelup";
		image.MakePixelPerfect();
		image.gameObject.SetActive(true);
		Vector3 pos = image.transform.localPosition;
		pos.y += 40f;
		TweenPosition posTween = TweenPosition.Begin(image.gameObject, 1f, pos);
		posTween.delay = 0.5f;

		Invoke("HideImage", 1f);
	}

	public void ShowGuardImage()
	{
		isDone = false;
		GetComponent<UIFollowTarget>().enabled = true;
		image.atlas = battleAtlas;
		image.spriteName = "battle_text_guard";
		image.MakePixelPerfect();
		image.gameObject.SetActive(true);
		Vector3 pos = image.transform.localPosition;
		pos.y += 40f;
		TweenPosition posTween = TweenPosition.Begin(image.gameObject, 1f, pos);
		posTween.delay = 0.5f;

		Invoke("HideImage", 0.5f);
	}

	void HideImage()
	{
		GetComponent<UIFollowTarget>().enabled = false;
		image.gameObject.SetActive(false);
		isDone = true;
	}

	IEnumerator Co_SetExpValue(int endValue)
	{
		float 	f 		= 0f;
		float 	pValue  = 0f;
		int curValue = 0;
		
		while( curValue < endValue ){
			curValue = (int)Mathf.Lerp(0, endValue,f);
			label.text = string.Format("+{0}",curValue); 
			f += Time.deltaTime/2;
			yield return null;
		}

		yield return new WaitForSeconds(1f);

		isDone = true;

		CheckIsLevelUp();
	}

	void CheckIsLevelUp()
	{
		GetComponent<UIFollowTarget>().enabled = false;
		label.gameObject.SetActive(false);
//		ShowLevelUpImage();
	}
}
